package priv.winnine.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import priv.winnine.entity.enums.ResultEnum;
import priv.winnine.entity.bo.ErrorProperties;
import priv.winnine.exception.ResultException;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.Set;

@Slf4j
public class BeanConvertUtil {

    public static <T> T convertBean(Validator validator, String requestString, Class<T> clazz) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            T t = objectMapper.readValue(requestString, clazz);
            Set<ConstraintViolation<T>> constraintViolationSet = validator.validate(t);
            if (constraintViolationSet.isEmpty()) {
                String request = objectMapper.writeValueAsString(t);
                if (log.isDebugEnabled()) {
                    log.info("request-bean = {}", request);
                }
            } else {
                constraintViolationSet.forEach(item -> {
                    throw new ResultException(ResultEnum.PROPERTY_ERROR, ErrorProperties.builder()
                            .message(item.getMessage())
                            .property(item.getPropertyPath().toString())
                            .build());
                });
            }
            return t;
        } catch (ResultException re) {
            throw re;
        } catch (Exception e) {
            if (e.getCause() instanceof ResultException) {
                throw (ResultException) e.getCause();
            }
            log.error(e.getMessage(), e);
            throw new ResultException(ResultEnum.PROPERTY_ERROR);
        }
    }

}
